package com.edu.cdp.controller;

import com.edu.cdp.VO.CategoryVO;
import com.edu.cdp.common.Result;
import com.edu.cdp.domain.Category;
import com.edu.cdp.service.CategoryService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/category")
@RestController
@Slf4j
@Tag(name = "商品分类相关接口")
public class CategoryController {
    @Autowired
    CategoryService categoryService;
    @GetMapping("/list")
    @Operation(summary = "获取商品分类列表")
    public Result<List<Category>> list() {
        List<Category> list = categoryService.list();

        return Result.success(list);
    }

    @PostMapping("/add")
    @Operation(summary = "添加商品分类")
    public Result<Category> add(
            @Parameter(name = "categoryName", description = "商品分类名称")
            String categoryName) {
        Category category = categoryService.add(categoryName);
        if (category != null) {
            return Result.success(category);
        } else {
            return Result.error("添加失败");
        }
    }

    @PutMapping("/update")
    @Operation(summary = "修改商品分类")
    public Result<Category> update(@ParameterObject Category category) {
        int result = categoryService.update(category);
        if (result > 0) {
            return Result.success(category);
        } else if (result == 0){
            return Result.error("该分类不存在");
        } else {
            return Result.error("修改失败");
        }
    }

    @DeleteMapping("delete")
    @Operation(summary = "删除商品分类")
    public Result<String> delete(
            @Parameter(name = "id", description = "商品分类id")
            Integer id) {
        categoryService.delete(id);

        return Result.success("操作成功");
    }

    @GetMapping("/fuzzy")
    @Operation(summary = "模糊查询商品分类")
    public Result<List<Category>> get(String categoryName) {
        List<Category> lists = categoryService.fuzzQuery(categoryName);

        if (lists.size() == 0) {
            return Result.error("查无此分类");
        }
        return Result.success(lists);
    }

    @GetMapping("/detail")
    @Operation(summary = "商品分类详情")
    public Result<CategoryVO> detail(
            @Parameter(name = "id", description = "商品分类id")
            Integer id) {
        CategoryVO categoryDetail = categoryService.getDetail(id);
        if (categoryDetail == null) {
            return Result.error("查无此分类");
        }
        return Result.success(categoryDetail);
    }
}
